import { Component, OnInit } from '@angular/core';
import { TimeService } from '../../service/timeservice/time.service';
import { ViewEncapsulation, ViewChild } from '@angular/core';
import { PopupComponent, SkinType } from 'ngx-weui';
import { DialogConfig, DialogComponent } from 'ngx-weui/dialog';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { HttpService } from '../../service/http.service';
declare const wx: any;

@Component({
  selector: 'contrement',
  templateUrl: './contrement.component.html',
  styleUrls: ['./contrement.component.css'],
  encapsulation: ViewEncapsulation.None
})

export class ContrementComponent implements OnInit {

  @ViewChild('simple') simplePopup: PopupComponent; // 底部
  @ViewChild('auto') autoAS: DialogComponent;
  //添加就诊人接口
  addpatienturl = 'patient!bindWithWX';
  //在线建档接口
  addpatientonlineurl = 'patient!getHisPatientInfo';
  payurl = 'wxpay!pay';

  radio: any; // 就诊人选择按钮
  //根据账号判断是否显示有就诊人
  patitentshow: boolean;
  patientindex: number;
  //添加就诊人的必须字段
  name: string;
  idcard: string;
  mobile: string;
  //排班日期
  schedulingdate: {
    date: string,
    week: string
  }
  //排班的信息字段
  scheduling: {
    DJ: string,
    FSD: string,
    FWMC: string,
    HCXH: string,
    HL: string,
    HM: string,
    HYMC: string,
    KGSJ: string,
    KSID: string,
    KSMC: string,
    SYHS: string,
    XMID: string,
    YGHS: string,
    YS: string,
    YSID: string,
    ZC: string
  }
  // timeinfo: {
  //   timeId: number,
  //   time: string
  // }

  type: number;
  rtype: number;
  time: any; // 所有的时间
  time1: any[] = []; // 前四个时间
  time2: any[] = []; // 后面的所有时间
  shown = false; // 判断是否展示更多
  icon = true; // weui-icon-checked
  num = 0; // tag是编辑还是确认
  reshow = false;
  textdown = '展开更多';
  // 为单选按钮定义的res
  res: any = {
    cho2: true,
    agree: true
  };
  checkbox: any; // 时间按钮，也是单选按钮，每次只能选择一个时间

  index: number; // 选择的就诊人的index

  // 对话框的内容及实现的函数
  private DEFCONFIG: DialogConfig = <DialogConfig>{
    title: '预约说明',
    confirm: '确定',
  };
  config: DialogConfig = {};

  constructor(private service: TimeService, private router: Router, private routerdata: ActivatedRoute, private httpservice: HttpService) {
    //this.time = this.service.time;
    //this.checkbox = this.time; // 时间列表
    //this.radio = this.service.person; // 就诊人列表
    //this.res.radio = this.radio[0]; // 默认选中第一个
    //this.res.checkbox = this.checkbox[0]; // 默认选中第一个
    // this.time1 = [];
    // this.time2 = [];
    // const c = [];
    // // 将前四个时间装入time1
    // for (let i = 0; i < 4; i++) {
    //   c.push(this.time[i]);
    //   this.time1.push(c[i]);

    // }
    // // 将剩下的时间装入time2
    // for (let i = 4; i < this.time.length; i++) {
    //   c.push(this.time[i]);
    //   this.time2.push(c[i]);
    // }

  }

  ngOnInit() {
    this.scheduling = JSON.parse(sessionStorage.getItem('scheduling'));
    this.time1 = [];
    this.time1.push(this.scheduling.KGSJ);
    this.schedulingdate = JSON.parse(sessionStorage.getItem('schedulingdate'));
    if (sessionStorage.getItem('patientlist') == null) {
      this.patitentshow = true;
    } else {
      this.patitentshow = false;
      this.radio = JSON.parse(sessionStorage.getItem('patientlist'));
      this.res.radio = this.radio[0]
    }

    this.rtype = 1;
  }

  check(i) {
    this.patientindex = i;
    this.simplePopup.hide();
  }

  // 底部弹出框编辑按钮事件
  confirm() {
    this.icon = !this.icon;
    this.num++;
    if (this.num % 2 !== 0) {
      this.simplePopup.config.confirm = '完成';
    } else {
      this.simplePopup.config.confirm = '编辑';
    }
  }
  // 底部弹出框取消按钮事件
  cancel() {
    this.icon = true;
    this.simplePopup.config.confirm = '编辑';
  }
  //预约规则
  onShow(type: SkinType, style: 1 | 2 | 3) {
    this.config = Object.assign({}, this.DEFCONFIG, <DialogConfig>{
      skin: type,
      cancel: null,
      confirm: null,
      btns: null,
      backdrop: true,
      content: '<p align="left">1、预约说明：请完善就诊人信息，填写就诊人身份证号和就诊卡号（若有）等信息，若无就诊卡可先挂号，就诊前再到医院服务台办理。<br>' +
        '2、就诊说明：请于就诊日携带身份证、就诊卡（若有）和医保卡到医院服务台领取挂号凭证，到相关科室签到就诊；如果您是预约挂号，且就诊时签到的时间在预约时间段内，可优先就诊，否则需排队等候。<br>' +
        '3、退号说明：<br>' +
        '“当日挂号”：如需退号，请在就诊前办理<br>' +
        '“预约挂号”：如需退号，请在就诊当日之前办理。</p>'
    });
    switch (style) {
      case 2:
        this.config.confirm = '确定';
        break;
    }
    setTimeout(() => {
      (<DialogComponent>this[`${type}AS`]).show().subscribe((res: any) => {
        console.log('type', res);
      });
    }, 10);
    return false;
  }
  //进入编辑就诊人界面
  editPatient(i) {
    sessionStorage.setItem('patientinfo', JSON.stringify(this.radio[i]));
    this.router.navigate(['/patient/editpatient']);
  }

  // 实现展开更多的效果
  show() {
    this.shown = !this.shown;
    if (this.shown) {
      this.textdown = '收起';
    } else {
      this.textdown = '展开更多';
    }
  }
  //在线建档
  addpatientonline() {
    if (sessionStorage.getItem('patientlist') != null) {
      this.pay();
    } else {
      this.type = 1;
      let data = "{ZJH:'" + this.idcard + "',XM:'" + this.name + "',SJH:'" + this.mobile + "'}";
      this.httpservice.httpPost(this.addpatientonlineurl, data).subscribe(res => {
        if (this.httpservice.dataFilter(res)) {
          this.addPatient(res.data.BRID);
        }
      });
    }
  }
  //新增就诊人
  addPatient(brid) {
    let sex = this.httpservice.sex(this.idcard);
    let data = "{p_id_card:'" + this.idcard + "',p_name:'" + this.name + "',p_sex:'" + sex + "',p_tel:'" + this.mobile + "',p_brid:'" + brid + "',wx_openid:'" + sessionStorage.getItem('openid') + "'}";
    this.httpservice.httpPost(this.addpatienturl, data).subscribe(res => {
      if (this.httpservice.dataFilter(res)) {
        console.log(res.data);
        this.pay();
        ///this.schedulinglist = res.data.data;
        //sessionStorage.setItem('schedulingdate',JSON.stringify(this.schedulingdate[i][j]));
        //console.log('接口名称:' + this.schedulingurl, this.schedulinglist);
      }
    });
  }
  //挂号
  pay() {
    let startdate = this.scheduling.KGSJ.substring(0, 5);
    let data = "{body:'" + this.scheduling.HYMC + "',total_fee:'" + this.scheduling.DJ + "',openid:'" + sessionStorage.getItem('openid') + "',HM:'" + this.scheduling.HM + "',RQ:'" + startdate + "',HX:''}";
    this.httpservice.httpPost(this.payurl, data).subscribe(res => {
      console.log('res',res);
      if (this.httpservice.dataFilter(res)) {
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: res.data.appId, // 必填，公众号的唯一标识
          timestamp: res.data.timeStamp, // 必填，生成签名的时间戳
          nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
          signature: res.data.signature,// 必填，签名，见附录1
          jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.chooseWXPay({
          appId:res.data.appId,
          timestamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success:function(res){
            
          },
          error:function(res){
            alert("支付失败")
          }
        });
      }
    });
  }

  
}
